<template>
	<div class="sys-pos-container">
		<el-card shadow="hover">
			<el-form :model="state.queryParams" ref="queryForm" :inline="true">
				<el-form-item :label-width='70' label="Pid" prop="pid">
					<el-input placeholder="Pid" clearable class='ml10' @keyup.enter="handleQuery"
						v-model="state.queryParams.pid" />
				</el-form-item>
				<el-form-item label='日期'>
					<el-date-picker class='ml10' v-model='state.UTCDateRange' type='daterange' range-separator='至'
						start-placeholder='开始日期' end-placeholder='结束日期' :shortcuts='shortcuts'
						:disabled-date="disabledDate" @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item :label-width='70' label="客户">
					<el-select :clearable='true' class='ml10' v-model="state.queryParams.customerId" placeholder="请选择"
						filterable>
						<el-option v-for='item in state.customerDict' :key='item.value' :label='item.label'
							:value='item.value' />
					</el-select>
				</el-form-item>
				<el-form-item :label-width='70' label='省份'>
					<el-select :clearable='true' class='ml10' v-model='state.queryParams.province' placeholder='请选择'
						filterable>
						<el-option v-for='item in optionDict.provinceDict' :key='item.value' :label='item.label'
							:value='item.value' />
					</el-select>
				</el-form-item>
				<el-form-item :label-width='70' label="产品名称" prop="productName">
					<el-input placeholder="产品名称" clearable class='ml10' @keyup.enter="handleQuery"
						v-model="state.queryParams.productName" />
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'diDailyReport:query'">
							查询
						</el-button>
					</el-button-group>
				</el-form-item>
			</el-form>
		</el-card>
		<el-card shadow="hover" style="margin-top: 8px">
			<div ref="lineChart" id="lineChart" :style="{ width: '98%', height: '400px' }"></div>
		</el-card>
	</div>
</template>

<script lang="ts" setup name="diHourlyChartReport">
import { onMounted, onUnmounted, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import mittBus from '/@/utils/mitt';
import { convertLocalDate, datePickerShortcuts } from '/@/utils/formatTime';
import { getCurrentInstance } from "vue";
import { DiDailyReport } from '/@/api/models';
import SysDiDailyReportApi from '/@/api/delivery/hourlyChartReport';
import { nextTick } from 'vue';
import SysDiCustomerApi from '/@/api/delivery/customer';
import { optionDict } from '/@/const/dict.ts';
// 定义变量内容

const shortcuts = datePickerShortcuts();
const state = reactive({
	loading: false,
	data: [] as Array<DiDailyReport>,
	UTCDateRange: [new Date(), new Date()],
	total: 0 as any,
	queryParams: {
		pid: undefined,
		dateRange: [],
		productName: undefined,
		customerId: undefined,
		province: undefined,
	},
	editTitle: '',
	ser: [] as any,
	pidList: [] as any,
	pidCount: [] as any,
	list: [] as any,
	myChart: '',
	ordera: [] as any,
	requester: [] as any,
	customerDict: [],
});

onMounted(async () => {

	handleQuery();
	mittBus.on('submitRefresh', () => {
		handleQuery();
	});

	let internalInstance = getCurrentInstance();
	let echarts = internalInstance?.appContext.config.globalProperties.$echarts;
	const dom = document.getElementById("lineChart");
	state.myChart = echarts?.init(dom); // 初始化echarts实例

	echart();
	await customerDictQuery();

});

onUnmounted(() => {
	mittBus.off('submitRefresh');
});

const formatLocalDate = async () => {
	if (state.UTCDateRange[0] as string)
		state.UTCDateRange[0] = new Date(state.UTCDateRange[0]);
	if (state.UTCDateRange[1] as string)
		state.UTCDateRange[1] = new Date(state.UTCDateRange[1]);

	if (state.UTCDateRange)
		state.queryParams.dateRange = [convertLocalDate(state.UTCDateRange[0]), convertLocalDate(state.UTCDateRange[1])];
	else
		state.queryParams.dateRange = [];
}

// 查询操作
const handleQuery = async () => {
	state.ser = [];
	state.pidList = [];
	state.loading = true;
	await formatLocalDate();
	const res = await SysDiDailyReportApi().queryRecord(state.queryParams);
	state.data = res.data.result ?? [];
	state.total = res.data.result?.total;
	state.loading = false;
	state.list = state.data.list;

	for (let i = 0; i < state.list.length; i++) {
		state.pidList.push(state.list[i].pid);
		state.list[i].list.forEach((item: any) => {
			item.count = ((Number(item.orderCount) / Number(item.requestCount)) * 100).toFixed(2);
			item.count == 'NaN' ? item.count = 0 : item.count;
			state.pidCount.push(
				Number(item.count),
			)
			state.ordera.push(Number(item.orderCount))
			state.requester.push(Number(item.requestCount))

		});

		let orOdd = i % 2 == 0 ? 1 : 0;

		state.ser.push({
			name: state.list[i].pid,
			data: state.pidCount,
			type: 'line',
			smooth: true,
			// stack: 'Total',
			ordera: state.ordera,
			requester: state.requester,
			yAxisIndex: orOdd,
			// step: "middle", // 梯形线图

		})
		state.ordera.length == 24 ? state.ordera = [] : state.ordera;
		state.requester.length == 24 ? state.requester = [] : state.requester;
		state.pidCount = [];
	}

	// console.log(JSON.parse(JSON.stringify(state.ser)), JSON.parse(JSON.stringify(state.pidList)), 'serrrr');
	echart();
};


// 日期不可选范围
const disabledDate = (time: Record<string, any>): boolean => {
    const today = new Date(); // 获取今天的日期
    today.setHours(0, 0, 0, 0); // 将时间设置为当天的零点
    return time.getTime() > today.getTime(); // 禁用今天之后的所有日期
}

const echart = () => {
	const option = {
		title: {
			text: '分时图表'
		},
		tooltip: {
			trigger: 'item',
			axisPointer: { // 坐标轴指示器，坐标轴触发有效
				type: 'line' // 默认为直线，可选为：'line' | 'shadow'
			},
			formatter: (value: any) => {
				// console.log(value, 'value');
				// console.log(state.ser[value.seriesIndex].ordera[value.dataIndex], 'value2');
				// console.log(state.ordera[value.seriesIndex], 'value3');.
				// console.log(value.dataIndex, 'value4');


				return `<span style="width: 10px;
									height: 10px;
									background-color: ${value.color};
									border-radius: 50%;
									display: inline-block;
									margin-right: 5px;"></span>${value.seriesName} <br/>
						时间：${value.name} <br/>
						订单数：${state.ser[value.seriesIndex].ordera[value.dataIndex]} <br/>
						请求数：${state.ser[value.seriesIndex].requester[value.dataIndex]} <br/>
						百分比：${value.data}% <br/>`;
			}
		},
		legend: {
			data: state.pidList,
			width: '1000px'
		},
		grid: {
			left: '3%',
			right: '4%',
			bottom: '3%',
			containLabel: true
		},
		toolbox: {
			feature: {
				saveAsImage: {},
				dataView: {
					show: true
				},
				magicType: {
					type: ['line', 'bar'],

				}
			}
		},
		xAxis: {
			type: 'category',
			boundaryGap: false,
			data: ['0点', '1点', '2点', '3点', '4点', '5点', '6点', "7点", '8点', '9点', '10点', '11点', '12点', '13点', '14点', '15点', '16点', '17点', '18点', '19点', '20点', '21点', '22点', '23点'],


		},
		yAxis: [
			{
				type: 'value',
				// splitLine: { //修改背景线条样式
				// 	show: false,//是否展示
				// 	lineStyle: {
				// 		color: "red",//线条颜色
				// 		type: "red"//线条样式，默认是实现，dashed是虚线
				// 	}
				// },

			},
			{
				type: 'value',
				position: 'right',
				name: '右侧Y轴名称',
				min: 0,
				// max: 5,
				// interval: 2,
				// splitNumber: 4, //设置坐标轴的分割段数
				axisTick: {
					// y轴刻度线
					show: false
				},
				splitLine: {
					// 网格线
					show: true,
					lineStyle: {
						color: ['rgba(255, 255, 255, 0.1)'],
						type: 'solid'
					}
				},
				splitArea: { show: false }, // 保留网格区域
				axisLabel: {
					// show: true,
					textStyle: {
						color: '#333'
					},
					// 这里重新定义就可以
					formatter: function (value) {
						var texts = [];
						if (value == 0) {
							texts.push('健康');
						} else if (value > 0 && value <= 1) {
							texts.push('低');
						} else if (value > 1 && value <= 2) {
							texts.push('中');
						} else if (value > 2 && value <= 3) {
							texts.push('高');
						} else if (value > 3) {
							texts = '极高';
						}
						return value;
					}
				},
				axisLine: {
					lineStyle: {
						type: 'solid',
						color: 'rgba(255, 255, 255, 0.37)' // 左边线的颜色
					}
				}

			}
		],
		series: state.ser

	}; // 图表配置参数
	// state.myChart?.setOption({}, true);
	// state.myChart?.clear();
	state.myChart?.setOption(option, true);
	state.myChart?.setOption(option);
	// 设置实例参数
	window.onresize = () => {
		state.myChart.resize();
	};
}


// 业务列表.
const customerDictQuery = async () => {
	await SysDiCustomerApi().queryAll({}).then((res) => {
		if (res.data.resCode === '0000')
			state.customerDict = res.data.result ?? [];
	});
};

</script>
